package com.block.datapush.service.apipush;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.common.util.AESOperator;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.MengXinHuaHuaSsqUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.mapper.MerchantThirdBaseInfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 萌薪花双授权
 */
@Service
public class MengXinHuaSsqApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    MerchantThirdBaseInfoMapper merchantThirdBaseInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String channel = pushApiKeyParam.getApiCode();
        String apiSecret = pushApiKeyParam.getApiSecret();
        String keyIv = pushApiKeyParam.getApiKey();
        String signKey = pushApiKeyParam.getPubKey();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("mobile_md5",memberSourceInfo.getMobileMd5());
        bizMap.put("name",memberSourceInfo.getRealname());
        bizMap.put("id_card",null);
        StringBuilder stringBuilder = new StringBuilder();
        String city = stringBuilder.append(memberSourceInfo.getProvince()).append("/").append(memberSourceInfo.getCity()).toString();
        bizMap.put("city",city);
        bizMap.put("loan_limit", MengXinHuaHuaSsqUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? 1 : 2);
        bizMap.put("age",memberSourceInfo.getAge());
        bizMap.put("operating_system_type","android");
        bizMap.put("ip", MengXinHuaHuaSsqUtil.getReqIp(memberSourceInfo.getReqIp()));
        bizMap.put("sesame_points", MengXinHuaHuaSsqUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("car", MengXinHuaHuaSsqUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("house", MengXinHuaHuaSsqUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("fund", MengXinHuaHuaSsqUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("social", MengXinHuaHuaSsqUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("insurance", MengXinHuaHuaSsqUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("businessLicense", 1);
        bizMap.put("iou_quota", MengXinHuaHuaSsqUtil.getBaitiao(memberSourceInfo.getBaitiao()));
        bizMap.put("flowers_quota", MengXinHuaHuaSsqUtil.getHuabei(memberSourceInfo.getHuabei()));
        bizMap.put("credit_card", MengXinHuaHuaSsqUtil.getXinyongka(memberSourceInfo.getXinyongka()));
        bizMap.put("expect_status", MengXinHuaHuaSsqUtil.getyuqi(memberSourceInfo.getYuqi()));

        String body = AESOperator.encrypt1(JSON.toJSONString(bizMap), apiSecret, keyIv);
        Long timestamp = System.currentTimeMillis() / 1000;
        StringBuilder signBuilder = new StringBuilder();
        String s = signBuilder.append(channel).append(body).append(timestamp).append(signKey).toString();
        String signStr = SecureUtil.md5(s);


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("data", body);
        paramMap.put("sign", signStr);
        paramMap.put("channel", channel);
        paramMap.put("timestamp", timestamp);

        log.info("【萌薪花下游双授权】撞库开始【queryUrl】{}【bizMap】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);

        log.info("【萌薪花下游双授权】撞库结束【resultDes】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");
        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (code == 0) {
            JSONObject data1 = resultObject.getJSONObject("data");
            String orderNum = UUID.randomUUID().toString();
            Integer status = data1.getInteger("status");
            pushApiResult.setCode(code + "|" + status);
            if (status != 1){
                pushApiResult.setPushSuccess(false);
                return pushApiResult;
            }
            String logo = data1.getString("logo_url");
            String name = data1.getString("product_name");
            String companyName = data1.getString("company_name");

            // 撞库成功之后，商户的机构数据存储
            ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
            thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
            thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
            thirdInfoDTO.setOrderNo(orderNo);
            JSONObject infoObject = new JSONObject();
            infoObject.put("orderNo",orderNum);
            infoObject.put("productId",orderNum);
            infoObject.put("productName",name);
            infoObject.put("companyName",companyName);
            infoObject.put("companyLogo",logo);
            infoObject.put("maxLoanAmount","200000");
            infoObject.put("maxLoanRate","20");
            infoObject.put("minLoanRate","1");
            infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            String name1 = data1.getString("agreements_title");
            String url = data1.getString("agreements_url");
            jsonObject.put("protocalName",name1);
            jsonObject.put("protocalUrl",url);
            jsonArray.add(jsonObject);
            infoObject.put("protocalList",jsonArray);
            thirdInfoDTO.setInfoObject(infoObject);

            //进行分润操作
            String priceType = pushApiKeyParam.getPriceType();
            BigDecimal typeRate = pushApiKeyParam.getTypeRate();
            if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                String price1 = data1.getString("price");//下游返回分润后价格
                if (StringUtils.isNotEmpty(price1)){
                    BigDecimal price = new BigDecimal(price1);
                    if (price.compareTo(new BigDecimal(0.00)) == -1){
                        pushApiResult.setPushSuccess(false);
                        return pushApiResult;
                    }
                    BigDecimal priceLeft = price.divide(typeRate);//分润前价格
                    pushApiResult.setPrice(priceLeft);
                    pushApiResult.setPriceRight(price);
                }
            }

            boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
            if (save){
                pushApiResult.setPushSuccess(true);
                pushApiResult.setOutOrderNo(orderNum);
                extJson.put("orderNum", orderNum);
                extJson.put("productId", orderNum);
            }else{
                pushApiResult.setMessage("保存撞库数据失败");
            }

        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String tid = extJson.getString("orderNum");
        String productId = extJson.getString("productId");

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        String channel = pushApiKeyParam.getApiCode();
        String apiSecret = pushApiKeyParam.getApiSecret();
        String keyIv = pushApiKeyParam.getApiKey();
        String signKey = pushApiKeyParam.getPubKey();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("mobile",memberSourceInfo.getMobile());
        bizMap.put("name",memberSourceInfo.getRealname());
        bizMap.put("id_card",null);
        StringBuilder stringBuilder = new StringBuilder();
        String city = stringBuilder.append(memberSourceInfo.getProvince()).append("/").append(memberSourceInfo.getCity()).toString();
        bizMap.put("city",city);
        bizMap.put("loan_limit", MengXinHuaHuaSsqUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? 1 : 2);
        bizMap.put("age",memberSourceInfo.getAge());
        bizMap.put("operating_system_type","android");
        bizMap.put("ip", MengXinHuaHuaSsqUtil.getReqIp(memberSourceInfo.getReqIp()));
        bizMap.put("sesame_points", MengXinHuaHuaSsqUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("car", MengXinHuaHuaSsqUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("house", MengXinHuaHuaSsqUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("fund", MengXinHuaHuaSsqUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("social", MengXinHuaHuaSsqUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("insurance", MengXinHuaHuaSsqUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("businessLicense", 1);
        bizMap.put("iou_quota", MengXinHuaHuaSsqUtil.getBaitiao(memberSourceInfo.getBaitiao()));
        bizMap.put("flowers_quota", MengXinHuaHuaSsqUtil.getHuabei(memberSourceInfo.getHuabei()));
        bizMap.put("credit_card", MengXinHuaHuaSsqUtil.getXinyongka(memberSourceInfo.getXinyongka()));
        bizMap.put("expect_status", MengXinHuaHuaSsqUtil.getyuqi(memberSourceInfo.getYuqi()));

        String body = AESOperator.encrypt1(JSON.toJSONString(bizMap), apiSecret, keyIv);
        Long timestamp = System.currentTimeMillis() / 1000;
        StringBuilder signBuilder = new StringBuilder();
        String s = signBuilder.append(channel).append(body).append(timestamp).append(signKey).toString();
        String signStr = SecureUtil.md5(s);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("data", body);
        paramMap.put("sign", signStr);
        paramMap.put("channel", channel);
        paramMap.put("timestamp", timestamp);

        log.info("【萌薪花下游双授权】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);


        log.info("【萌薪花下游双授权】导单结束【result】{}", resultObject.toJSONString());


        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo );
        thirdInfoDTO.setRetCode(String.valueOf(code));
        thirdInfoDTO.setRetMsg(msg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (code == 0){
            JSONObject data = resultObject.getJSONObject("data");
            Integer status = data.getInteger("status");
            thirdInfoDTO.setRetCode(String.valueOf(code) + "|" + status);
            if (status == 1){
                thirdInfoDTO.setStatus("SUCCESS");
            }
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);
        if (code == 0) {
            JSONObject data = resultObject.getJSONObject("data");
            Integer status = data.getInteger("status");
            pushApiResult.setCode(code + "|" + status);
            if (status == 1){
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(true);
                pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
                return pushApiResult;
            }
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }


}
